﻿Imports mshtml
Imports SHDocVw
Imports Microsoft.Win32
Imports System.Runtime.InteropServices
Imports System.Web

Public Class AntiPorn

    Dim ie_instances As New ArrayList
    Dim m_settings_loaded = False

    Private Sub AntiPorn_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Hide()
        setAutoStartup()

        Dim shellWindows As SHDocVw.ShellWindows = New SHDocVw.ShellWindows()
        AddHandler shellWindows.WindowRegistered, AddressOf windowOpened
        AddHandler shellWindows.WindowRevoked, AddressOf windowClosed

        AP_Username = getStoredUser()
        AP_Password = getStoredPassword()

        If AP_Username = Nothing And AP_Password = Nothing Then
            Me.Show()
            Me.WindowState = FormWindowState.Normal       
        End If

    End Sub

    Private Function checkLogin(ByVal quit As Boolean) As Boolean
        AP_Username = getStoredUser()
        AP_Password = getStoredPassword()
        Dim flag As Boolean = False

        AP_Username = UsernameTextBox.Text
        AP_Password = getMD5Hash(PasswordTextBox.Text)
        saveUserPass()
        Dim resp = getWebPagePOST(AP_Server + "rpc_login_p.php", "u=" + AP_Username + "&p=" + AP_Password)
        If Not resp = "Unauthorized" Then
            flag = True
            UsernameTextBox.Enabled = False
        End If

        If Not flag Then
            If quit Then
                MsgBox("Please enter the user/password to exit!")
            Else
                MsgBox("User/Password Incorrect")
            End If            
        End If
        Return flag
    End Function

    Private Sub windowOpened(ByVal cookie As Integer)
        If m_settings_loaded = False Then
            'Browser opening for the first time...
            loadSettings(AP_Username, AP_Password)
            m_settings_loaded = True
        End If

        Dim shellWindows As SHDocVw.ShellWindows = New SHDocVw.ShellWindows()
        Dim filename As String
        Dim browser As SHDocVw.InternetExplorer

        For Each ie As SHDocVw.InternetExplorer In shellWindows
            filename = System.IO.Path.GetFileNameWithoutExtension(ie.FullName).ToLower()

            If filename = "iexplore" Then
                If Not ie_instances.Contains(ie) Then
                    browser = ie
                    AddHandler browser.BeforeNavigate2, AddressOf beforeNavigate                    
                    ie_instances.Add(cookie)
                End If
            End If
        Next
    End Sub

    Private Sub beforeNavigate(ByVal pDisp As Object, ByRef URL As Object, ByRef flags As Object, ByRef targetFrameName As Object, ByRef postData As Object, ByRef headers As Object, ByRef cancel As Boolean)
        Dim CurrentURL As String = URL
        Dim browser As SHDocVw.InternetExplorer = pDisp

        If Not Trim(CurrentURL).StartsWith("http") Then
            Return
        End If

        'log the request
        logRequest(AP_Username, AP_Password, CurrentURL)

        'check if the site is excluded .. nothing must block it
        Dim array As String() = Settings_ExcludeSites.Split(",")
        For Each m_site As String In array
            If CurrentURL.ToLower.IndexOf(m_site.ToLower) <> -1 Then
                'Just load normally
                Return
            End If
        Next

        'check if the site is blocked
        Dim array2 As String() = Settings_BlockSites.Split(",")
        For Each m_site As String In array2
            If CurrentURL.ToLower.IndexOf(m_site.ToLower) <> -1 Then
                AddHandler browser.DocumentComplete, AddressOf documentCompleteDisplayError
                Return
            End If
        Next

        'check urlblacklist.com data
        If Settings_URLBlacklistMode = "1" Then
            Dim resp = getWebPageGET(AP_Server + "urlblacklist.php?url=" + HttpUtility.UrlEncode(CurrentURL))
            If resp = "stop" Then
                AddHandler browser.DocumentComplete, AddressOf documentCompleteDisplayError
                Return
            End If
        End If

        'proceed for keywords analysis after document is loaded completely
        AddHandler browser.DocumentComplete, AddressOf documentComplete
    End Sub

    Private Sub windowClosed(ByVal cookie As Integer)
        If ie_instances.Contains(cookie) Then
            ie_instances.Remove(cookie)
        End If
    End Sub

    Private Sub documentCompleteDisplayError(ByVal pDisp As Object, ByRef URL As Object)
        Dim browser As WebBrowser = pDisp
        Dim myDoc As mshtml.IHTMLDocument2
        myDoc = browser.Document
        myDoc.url = "res://ieframe.dll/"
        RemoveHandler browser.DocumentComplete, AddressOf documentCompleteDisplayError
    End Sub

    Private Sub documentComplete(ByVal pDisp As Object, ByRef URL As Object)
        Dim browser As WebBrowser = pDisp
        Dim myDoc As mshtml.IHTMLDocument2
        myDoc = browser.Document
        If myDoc.url = "about:blank" Then
            Return
        End If

        'check for keywords
        Dim array2 As String() = Settings_BadKeywords.Split(",")
        For Each m_kw As String In array2
            If myDoc.body.innerHTML.ToLower.IndexOf(m_kw.ToLower) <> -1 Then
                Dim origHtml As String = myDoc.body.innerHTML
                myDoc.body.innerHTML = "<div style='cursor:progress; width=100%; height: 100%;'></div>"
                Dim resp = getWebPagePOST(AP_Server + "rpc_access_p.php", "u=" + AP_Username + "&p=" + AP_Password + "&c=" + getComputer() + "&url=" + HttpUtility.UrlEncode(myDoc.url))
                If resp = "stop" Then
                    myDoc.url = "res://ieframe.dll/"
                    RemoveHandler browser.DocumentComplete, AddressOf documentComplete
                    Return
                Else
                    myDoc.body.innerHTML = origHtml
                    RemoveHandler browser.DocumentComplete, AddressOf documentComplete
                    Return
                End If
            End If
        Next

        'if nothing matches, just proceed but remove the listener
        RemoveHandler browser.DocumentComplete, AddressOf documentComplete
    End Sub

    Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel.Click
        ExitApp()
    End Sub

    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
        If checkLogin(False) Then
            Me.Hide()
            PasswordTextBox.Text = ""
        End If
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        ExitApp()
    End Sub

    Private Sub AntiPornWebsiteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AntiPornWebsiteToolStripMenuItem.Click
        Process.Start(AP_Server)
    End Sub

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        MsgBox("Anti-Porn" + vbCrLf + "Felix Softwares Pty Ltd © 2011" + vbCrLf + "ACN 145 712 170" + vbCrLf + "felsoft.com.au", MsgBoxStyle.Information, "About Anti-Porn")
    End Sub

    Private Sub ChangeLoginCredencialsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChangeLoginCredencialsToolStripMenuItem.Click
        Me.Show()
        Me.WindowState = FormWindowState.Normal
        UsernameTextBox.Text = getStoredUser()
        PasswordTextBox.Text = ""
    End Sub

    Private Sub NotifyIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon.MouseDoubleClick
        Me.Show()
        Me.WindowState = FormWindowState.Normal
        UsernameTextBox.Text = getStoredUser()
        PasswordTextBox.Text = ""
    End Sub

    Private Sub ExitApp()
        Application.Exit()
    End Sub
End Class